﻿function CodeBasePopup()
{
    validator = null;
    ViewBagEdit = -1;
    ObjectKey = "";

    //var URL Action Save
    UrlSave = "";

    //Key Old
    KeyOld = "";
    KeyJustNew = "";

    
    TopFixHeight = 100;
    BottomFixHeight = 50;

    objControls = null;

    this.entityDetail = "";

    objControlsGrid = null;
    var ControlNotShow = new Array();
    var GridViewNamePopup;

    ValueBeforeEdit = null;

    this.init = function (_ViewBagEdit, _ObjectKey, _UrlSave, _KeyOld, _gridName, _TopFixHeight, _BottomFixHeight) {

        if (typeof _gridName != "undefined")
            GridViewNamePopup = _gridName.split(",");
        else
            GridViewNamePopup = "".split(",");
        if (typeof _TopFixHeight != 'undefined')
            TopFixHeight = _TopFixHeight;

        if (typeof _BottomFixHeight != 'undefined'){
            BottomFixHeight = _BottomFixHeight;
        }
        ViewBagEdit = _ViewBagEdit;
        ObjectKey = _ObjectKey;
        UrlSave = _UrlSave;
        KeyOld = _KeyOld;
        

        validator = $('#frm').kendoValidator().data("kendoValidator");

        HideBusy("pupopBusy");

        //// focus the widget
        //$(document).on("keydown.divpupup", function (e) {
        //    if (e.keyCode === 27 /* w */) {
        //        codeBasePopup.Close();
        //    }
        //    if (e.keyCode === 13 /* w */) {
        //        if (typeof SavePopup != "undefined")
        //            SavePopup();
        //        else
        //            codeBasePopup.SavePopup();
        //    }
        //});

        if (!IsNullOrEmty(_ObjectKey))
            $('#' + ObjectKey).unbind().bind('focusout', function () {
            var _code = $('#' + ObjectKey).val();
            if (_code != null)
                $('#' + ObjectKey).val(_code.toUpperCase());

        });

        
        resizePopup();            
        
        
        $(window).resize(function ()
        {
            resizePopup();
            
        });

        if (ObjectControl.length > 10) {
            ObjectControl = ObjectControl.substring(0, ObjectControl.length - 1) + ']}';
            objControls = $.parseJSON(ObjectControl);
            $(objControls.data).each(function (i) {
                var o = objControls.data[i];
                if (o.controltype == "checkbox") {
                    var c = $('input[id=' + o.name + ']');
                    if (!IsNull(c)) {
                        c.change(function () {
                            if (typeof onPropertyChanged != 'undefined') {
                                var name = this.id;
                                var check = $(this).is(':checked');
                                onPropertyChanged(name, null, check);
                            }
                        });
                        c.focusout(function () { lostFocus(o.name); });
                        c.keydown(function (e, i) { keyDown(e, o.name); });
                    }
                }
                else if (o.controltype == "text") {
                    var myInput = document.getElementById(o.name);
                    if (!IsNull(myInput)) {
                        attachTextListener(myInput, function () {
                            if (typeof onPropertyChanged != 'undefined') {
                                var name = this.id;
                                var value = this.value;
                                onPropertyChanged(name, null, value);
                            }

                        });
                        $(myInput).focusout(function () { lostFocus(o.name); });
                        $(myInput).keydown(function (e, i) { keyDown(e, o.name); });
                    }
                }
                else if (o.controltype == "numeric") {
                    var numerictextbox = $("#" + o.name + "").data("kendoNumericTextBox");
                    if (!IsNull(numerictextbox)) {
                        // bind to the change event
                        numerictextbox.bind("change", function (e) {
                            if (typeof onPropertyChanged != 'undefined') {
                                var name = this.wrapper.context.id;
                                var old = this._old;
                                var newv = this._value;
                                onPropertyChanged(name, old, newv);
                            }
                        });
                        $(numerictextbox.element[0]).focusout(function () { lostFocus(o.name); });
                        $(numerictextbox.element[0]).keydown(function (e, i) { keyDown(e, o.name); });
                    }
                }
                else if (o.controltype == "date") {
                    var datePicker = $("#" + o.name + "").data("kendoDatePicker");
                    // bind to the change event
                    if (!IsNull(datePicker)) {
                        datePicker.bind("change", function (e) {
                            if (typeof onPropertyChanged != 'undefined') {
                                var name = this.wrapper.context.id;
                                var old = this._old;
                                var newv = this._value;
                                onPropertyChanged(name, old, newv);
                            }
                        });

                        $(datePicker.element[0]).focusout(function () { lostFocus(o.name); });
                        $(datePicker.element[0]).keydown(function (e, i) { keyDown(e, o.name); });
                    }
                }
                else if (o.controltype == "combobox") {
                    // get a reference to instance of the Kendo UI ComboBox
                    var combobox = $("#" + o.name + "").data("kendoComboBox");
                    // bind to the change event
                    if (!IsNull(combobox)) {
                        combobox.bind("change", function (e) {
                            if (typeof onPropertyChanged != 'undefined') {
                                var name = this.wrapper.context.id;
                                var old = this._old;
                                var newv = this._selectedValue;
                                onPropertyChanged(name, old, newv);
                            }

                        });
                        $(combobox.element[0]).focusout(function () { lostFocus(o.name); });
                        combobox.input.bind("keydown", function (e) {
                            keyDown(e, o.name);
                        });
                    }
                } else if (o.controltype == "lvcombobox") {
                    // get a reference to instance of the Kendo UI ComboBox
                    var combobox = $("#" + o.name + "").LVComboBox().data("LVComboBox");
                    // bind to the change event
                    if (!IsNull(combobox)) {
                        combobox.selectchange = function (old, n, m) {
                            if (typeof onPropertyChanged != 'undefined') {
                                var name = o.name;
                                var old = old;
                                var newv = n;
                                onPropertyChanged(name, old, newv);
                            }
                        };

                        combobox.InputControl().focusout(function () { lostFocus(o.name); });
                        combobox.InputControl().bind("keydown", function (e) {
                            keyDown(e, o.name);
                        });
                    }
                }
            });
        }

        for (var i = 0; i < GridViewNamePopup.length; i++) {
            if (IsNullOrEmty(GridViewNamePopup[i])) continue;
            var gridview = $("#" + GridViewNamePopup[i]).data("kendoGrid");
            gridview.bind("edit", this.grid_edit);


            gridview.bind("change", function (e) {
                var selectedRow = this.select();

                var dataItem = this.dataItem(selectedRow);

                if (typeof RowChange != 'undefined' && typeof dataItem != 'undefined') {
                    if (this.OldDataSelect == null || this.OldDataSelect != dataItem) {
                        if (!this.IsValidate)
                            RowChange(dataItem, this);
                        else
                            this.IsValidate = false;

                        this.OldDataSelect = dataItem;
                        this.OldRowSelect = selectedRow;
                    }
                }
            });

            gridview.bind("dataBound", function (e)
            {
            });

        }
       
        if (typeof ObjectControlGrid != 'undefined' && ObjectControlGrid!="") {
            ObjectControlGrid = '{ "data":[' + ObjectControlGrid + ']}';
            objControlsGrid = $.parseJSON(ObjectControlGrid);
        }

        if ($.getUrlVar("copy") == 1)
        {
            this.SetValue(ObjectKey, null);
        }

        if (ViewBagEdit == -1) {
            this.disableForm();
        }

        setTimeout(function ()
        {
            for (var name in modelview[0]) {
                var Exist = false;
                for (var j = 0; j < objControls.data.length; j++) {
                    if (objControls.data[j].name == name) {
                        Exist = true;
                        break;
                    }
                    Exist = false;
                }

                if (Exist == false)
                {
                    ControlNotShow.push(name);
                }
            }
                
            
        }, 5);
    };

    this.grid_edit = function (e) {
        var propertyEdit = "";
        var i = 0;
        var inputArray = e.container.find("input");
        for (i; i < inputArray.length; i++) {
            if (inputArray[i].id != "") {
                propertyEdit = inputArray[i].id;
                i = inputArray.length;
            }
        }


        if (typeof onGridEdit != 'undefined') {
          
            onGridEdit(e, propertyEdit);
        }

        RegisterPropertyChange(e, propertyEdit);
    };

    function RegisterPropertyChange(e, propertyEdit) {
        $(objControlsGrid.data).each(function (i) {
            var o = objControlsGrid.data[i];
            if (e.sender.wrapper.length >0 && e.sender.wrapper[0].id == o.gridname)
                {
                if (o.name == propertyEdit) {
                    if (o.controltype == "checkbox") {
                        var c = e.container.find("input[id=" + o.name + "]");
                        if (!IsNull(c)) {
                            c.change(function () {
                                if (typeof onPropertyChanged != 'undefined') {
                                    var name = this.id;
                                    var check = $(this).is(':checked');
                                    onPropertyChanged(name, null, check);
                                }
                                var gridview = $("#" + o.gridname).data("kendoGrid");
                                gridview.IsRowChanged = true;
                            });
                        }
                    }
                    else if (o.controltype == "text") {
                        var myInput = document.getElementById(o.name);
                        if (!IsNull(myInput)) {
                            attachTextListener(myInput, function () {
                                if (typeof onPropertyChanged != 'undefined') {
                                    var name = this.id;
                                    var value = this.value;
                                    onPropertyChanged(name, null, value);
                                }
                                var gridview = $("#" + o.gridname).data("kendoGrid");
                                gridview.IsRowChanged = true;
                            });
                        }
                    }
                    else if (o.controltype == "numeric") {
                        var numerictextbox = $("#" + o.name + "").data("kendoNumericTextBox");
                        // bind to the change event
                        if (!IsNull(numerictextbox)) {
                            numerictextbox.bind("change", function (e) {
                                if (typeof onPropertyChanged != 'undefined') {
                                    var name = this.wrapper.context.id;
                                    var old = this._old;
                                    var newv = this._value;
                                    onPropertyChanged(name, old, newv);
                                }
                                var gridview = $("#" + o.gridname).data("kendoGrid");
                                gridview.IsRowChanged = true;
                            });
                        }
                    }
                    else if (o.controltype == "date") {
                        var datePicker = $("#" + o.name + "").data("kendoDatePicker");
                        if (!IsNull(datePicker)) {
                            // bind to the change event
                            datePicker.bind("change", function (e) {
                                if (typeof onPropertyChanged != 'undefined') {
                                    var name = this.wrapper.context.id;
                                    var old = this._old;
                                    var newv = this._value;
                                    onPropertyChanged(name, old, newv);
                                }
                                var gridview = $("#" + o.gridname).data("kendoGrid");
                                gridview.IsRowChanged = true;
                            });
                        }
                    }
                    else if (o.controltype == "combobox") {
                        // get a reference to instance of the Kendo UI ComboBox
                        var combobox = $("#" + o.name + "").data("kendoComboBox");

                        var grid = $("#" + o.gridname).data("kendoGrid");
                        var model = GetCurrentRowEx(grid);

                        if (!IsNull(model))
                            ValueBeforeEdit = model[o.name];
                        else
                            ValueBeforeEdit = null;

                        // bind to the change event
                        if (!IsNull(combobox)) {
                            combobox.bind("change", function (e) {
                                var name = this.wrapper.context.id;

                                var gridview = $("#" + o.gridname).data("kendoGrid");
                                var model = GetCurrentRowEx(gridview);

                                var old = this._old;
                                var newv = this._selectedValue;

                                if (ValueBeforeEdit != newv) {
                                    ValueBeforeEdit = "undefined";
                                    if (typeof onPropertyChanged != 'undefined') {
                                        model[name] = this._selectedValue;
                                        onPropertyChanged(name, old, newv);
                                    }
                                    gridview.IsRowChanged = true;
                                }
                                //combox column binding với giá trị null lỗi


                                if (typeof model != 'undefined' && model[o.name] == "[object Object]") {
                                    model[o.name] = this._selectedValue;
                                }

                            });
                        }
                    }
                    else if (o.controltype == "lvcombobox") {
                        var combobox = $("#" + o.name + "").LVComboBox().data("LVComboBox");
                        // bind to the change event
                        if (!IsNull(combobox)) {
                            combobox.selectchange = function (old, n, m) {
                                if (typeof onPropertyChanged != 'undefined') {
                                    var name = o.name;
                                    var old = old;
                                    var newv = n;

                                    var gridview = $("#" + o.gridname).data("kendoGrid");
                                    var model = GetCurrentRowEx(gridview);

                                    model[name] = newv;

                                    onPropertyChanged(name, old, newv);
                                }

                                var gridview = $("#" + o.gridname).data("kendoGrid");
                                gridview.IsRowChanged = true;
                            };
                        }
                    }
                }
            }
        });
    }

    function resizePopup()
    {
        if(TopFixHeight==-1 || BottomFixHeight ==-1) return;
        var form = document.forms[0];
        var w = $(window).width();
        
        $(form).height($(window).height() - 40);
        var h = $(window).height() - TopFixHeight - BottomFixHeight;
        var container = $("#_blank");
        if (container) {
            container.width(w);
        }

        var inTab = 0;
        if (container.length > 0)
        {
            var _bl = $(container[0]);
            if (_bl.length > 0)
            {
                var _div = $(_bl[0]);
                _div.find(".k-content").each(function (i, o)
                {
                    var tab = $(o);
                    //tab.width(w - 33);
                    tab.height(h - 10);
                    inTab = 1;
                });
                
            }
        }

        for (var i = 0; i < GridViewNamePopup.length; i++) {
            if (IsNullOrEmty(GridViewNamePopup[i])) continue;
            var grid = $("#" + GridViewNamePopup[i]);

            if (inTab == 1) {
                grid.height(h - 15);
                grid.width(w - 8);
            }
            else {
                if (i != 0 || GridViewNamePopup.length==1) grid.height(h - 10);
                grid.width(w - 5);
            }

            if ((i == 0 && GridViewNamePopup.length > 1) && inTab == 0) continue;

            var dataArea = grid.find(".k-grid-content");
            var gridHeight = grid.innerHeight();
            var otherElements = grid.children().not(".k-grid-content");
            var otherElementsHeight = 0;

            otherElements.each(function () {
                otherElementsHeight += $(this).outerHeight();
            });

            dataArea.height(gridHeight - otherElementsHeight);

            $("#" + GridViewNamePopup[i]).data("kendoGrid").refresh();
        }
        
    }

    this.Close = function () {
        if (ViewBagEdit == 0) 
            closeWindow(1, KeyJustNew, idWindow);
        else
            closeWindow(0, "", idWindow);
    };

    this.SavePopup = function () {
        if (!IsNull(validator) && !validator.validate()) {
            var errors = validator.errors();
            var errormsg = "";
            $(errors).each(function () {
                errormsg = errormsg + " - " + this;
                
            });

            ShowMessageError('', errormsg);
            
            return;
        }

        var form=null;
        if(document.forms.length >0)
            form = document.forms[0];

        //Lấy controller 
        var url = UrlSave ;
        if ($.getUrlVar("copy") == 1) {
            url = url + '?Edit=0&ID=' + KeyOld;
        }
        else
            url = url + '?Edit=' + ViewBagEdit + '&ID=' + KeyOld;

        if (typeof OnChangeUrl != 'undefined') {
            url = OnChangeUrl(url);
        }

        //lấy model và gửi lên controller xử lý
        var diverror = document.getElementById('diverror');

        ShowBusy("pupopBusy");

        var datastring = "";
        if (!IsNull(form)) {
            datastring = jQuery(form).serializeCustom();

            for (var i = 0; i < ControlNotShow.length; i++) {
                if (ControlNotShow[i].indexOf("_") < 0 && modelview[0][ControlNotShow[i]] != null)
                    datastring = datastring + '&' + ControlNotShow[i] + '=' + modelview[0][ControlNotShow[i]];
            }
        }

        for (var i = 0; i < GridViewNamePopup.length; i++) {
            if (IsNullOrEmty(GridViewNamePopup[i])) continue;
            var grid = $("#" + GridViewNamePopup[i]).data("kendoGrid");

            datastring = datastring + '&' + this.entityDetail[i] + '=' + JSON.stringify(grid.dataSource.data());
        }
       

        $.post(url, datastring, function (data) {
            if (data != "0") {
                ShowMessageError('', data);

                if (typeof PopupSaveError != 'undefined')
                    PopupSaveError(data);
            }
            else {
                var _cancel = false;
                if (typeof PopupSaveCompleted != 'undefined')
                    _cancel = PopupSaveCompleted();

                if (!_cancel) {
                    var _keyTemp = "";
                    if (!IsNullOrEmty(ObjectKey)) {
                        if (document.getElementById(ObjectKey) != null)
                            _keyTemp = document.getElementById(ObjectKey).value;
                        if (ViewBagEdit == 0 && $.getUrlVar("copy") != 1) {
                            KeyJustNew = _keyTemp;
                            codeBasePopup.clearControl();
                            $("#" + ObjectKey).focus();
                        }
                        else
                            closeWindow(1, _keyTemp, idWindow);
                    }
                }
            }

            HideBusy("pupopBusy");
        });
    };

    this.OpenWindow = function (url, Title, WidthPopup, HeightPopup, Para1) {
        url = url.replace("!1", document.getElementById(Para1).value);

        //GolbalMessage.OpenWindow(url, Title, WidthPopup, HeightPopup);
    };

    this.disableForm = function () {
        $(objControls.data).each(function (i) {
            var o = objControls.data[i];
            
            if (o.controltype == "checkbox") {
                $('input[id=' + o.name + ']').attr("disabled", "disabled");
            }
            else if (o.controltype == "text") {
                $('input[id=' + o.name + ']').attr("disabled", "disabled");
            }
            else if (o.controltype == "numeric") {
                var numerictextbox = $("#" + o.name + "").data("kendoNumericTextBox");

                // bind to the change event
                numerictextbox.enable(false);
            }
            else if (o.controltype == "date") {
                var datePicker = $("#" + o.name + "").data("kendoDatePicker");
                datePicker.enable(false);
            }
            else if (o.controltype == "combobox") {
                // get a reference to instance of the Kendo UI ComboBox
                var combobox = $("#" + o.name + "").data("kendoComboBox");
                combobox.enable(false);
            }
            
            else if (o.controltype == "lvcombobox") {
                // get a reference to instance of the Kendo UI ComboBox
                var combobox = $("#" + o.name + "").LVComboBox().data("LVComboBox");
                combobox.enable(false);
            }
        });
    };

    this.clearControl = function () {
        var form = document.forms[0];
        var inputs, index;

        // Find its child `input` elements
        inputs = form.getElementsByTagName('input');

        for (index = 0; index < inputs.length; ++index) {
            if ((inputs[index]).type == "checkbox") {
                $("input:checkbox[name=" + inputs[index].id + "]").attr('checked', false);
            }
            else {
                var isSet = false;
                $(objControls.data).each(function (i) {
                    var o = objControls.data[i];
                    if (o.controltype == "numeric" && o.name == inputs[index].id) {
                        $(inputs[index]).attr("value", 0);
                        isSet = true;
                    }
                    
                });
                if(!isSet)
                        $(inputs[index]).val(null);
            }
        }

        for (var i = 0; i < GridViewNamePopup.length; i++) {
            if (IsNullOrEmty(GridViewNamePopup[i])) continue;
            var grid = $("#" + GridViewNamePopup[i]).data("kendoGrid");
            grid.dataSource.read();
            grid.refresh();
        }
       

        if (typeof SetDefaultValue != 'undefined')
            SetDefaultValue();
    };

    this.Add_record = function (gridviewname)
    {
        if (IsNullOrEmty(gridviewname) && !IsNull(GridViewNamePopup)) {
            for (var i = 0; i < GridViewNamePopup.length; i++) {
                if (IsNullOrEmty(GridViewNamePopup[i])) continue;
                var grid = $("#" + GridViewNamePopup[i]).data("kendoGrid");

                if (grid.dataSource.data().length == 0) {
                    grid.OldDataSelect = null;
                    grid.OldRowSelect = null;
                }

                grid.addRow();
                SelectLastRow(grid);
            }
        }
        else {
            var grid = $("#" + gridviewname).data("kendoGrid");

            if (grid.dataSource.data().length == 0) {
                grid.OldDataSelect = null;
                grid.OldRowSelect = null;
            }

            grid.addRow();
            SelectLastRow(grid);
        }
    }

    this.Delete_record = function (gridviewname)
    {
        if (IsNullOrEmty(gridviewname) && !IsNull(GridViewNamePopup)) {
            for (var i = 0; i < GridViewNamePopup.length; i++) {
                if (IsNullOrEmty(GridViewNamePopup[i])) continue;
                var grid = $("#" + GridViewNamePopup[i]).data("kendoGrid");

                grid.OldDataSelect = null;
                grid.OldRowSelect = null;

                grid.removeRow(grid.select());
                grid.refresh();
            }
        }
        else {
            if (!IsNull(gridviewname)) {
                var grid = $("#" + gridviewname).data("kendoGrid");

                grid.OldDataSelect = null;
                grid.OldRowSelect = null;

                grid.removeRow(grid.select());
                grid.refresh();
            }
        }
        
    }

    this.CheckReadOnly = function (fieldName) {
        var readonly = false;
        $(objControls.data).each(function (i) {
            var o = objControls.data[i];
            if (o.name == fieldName) {
                if (o.controltype == "checkbox") {
                    readonly = $('input[id=' + o.name + ']').is(":checked")
                }
                else if (o.controltype == "text") {
                    if ($('input[id=' + o.name + ']').attr('disabled') == 'disabled')
                        readonly = true;
                    else
                        readonly = false;
                }
                else if (o.controltype == "numeric") {
                    var numerictextbox = $("#" + o.name + "").data("kendoNumericTextBox");

                    // bind to the change event
                    if ($(numerictextbox.element[0]).attr('disabled') == 'disabled')
                        readonly = true;
                    else
                        readonly = false;
                }
                else if (o.controltype == "date") {
                    var datePicker = $("#" + o.name + "").data("kendoDatePicker");
                    if ($(datePicker.element[0]).attr('disabled') == 'disabled')
                        readonly = true;
                    else
                        readonly = false;
                }
                else if (o.controltype == "combobox") {
                    // get a reference to instance of the Kendo UI ComboBox
                    var combobox = $("#" + o.name + "").data("kendoComboBox");
                    if ($(combobox.element[0]).attr('disabled') == 'disabled')
                        readonly = true;
                    else
                        readonly = false;
                }
                else if (o.controltype == "lvcombobox") {
                    // get a reference to instance of the Kendo UI ComboBox
                    var combobox = $("#" + o.name + "").LVComboBox().data("LVComboBox");
                    combobox.enable();
                }
            }
        });
        return readonly;
    }

    this.IsReadOnly = function (fieldName, isReadOnly)
    {
        $(objControls.data).each(function (i) {
            var o = objControls.data[i];
            if (o.name == fieldName)
            {
                if (o.controltype == "checkbox") {
                    if (isReadOnly == true)
                        $('input[id=' + o.name + ']').attr("disabled", "disabled");
                    else
                        $('input[id=' + o.name + ']').removeAttr("disabled");
                }
                else if (o.controltype == "text") {
                    if (isReadOnly == true)
                        $('input[id=' + o.name + ']').attr("disabled", "disabled");
                    else
                        $('input[id=' + o.name + ']').removeAttr("disabled");
                }
                else if (o.controltype == "numeric") {
                    var numerictextbox = $("#" + o.name + "").data("kendoNumericTextBox");

                    // bind to the change event
                    if (isReadOnly == true)
                        numerictextbox.enable(false);
                    else
                        numerictextbox.enable();
                }
                else if (o.controltype == "date") {
                    var datePicker = $("#" + o.name + "").data("kendoDatePicker");
                    if (isReadOnly == true)
                        datePicker.enable(false);
                    else
                        datePicker.enable();
                }
                else if (o.controltype == "combobox") {
                    // get a reference to instance of the Kendo UI ComboBox
                    var combobox = $("#" + o.name + "").data("kendoComboBox");
                    if (isReadOnly == true)
                        combobox.enable(false);
                    else
                        combobox.enable();
                }
                else if (o.controltype == "lvcombobox") {
                    // get a reference to instance of the Kendo UI ComboBox
                    var combobox = $("#" + o.name + "").LVComboBox().data("LVComboBox");
                    if (isReadOnly == true)
                        combobox.enable(false);
                    else
                        combobox.enable(true);
                }
            }
        });
    }

    this.SetValue = function (fieldName, value,focus) {
        var isSeted = false;
        $(objControls.data).each(function (i) {
            var o = objControls.data[i];
            if (o.name == fieldName) {
                if (o.controltype == "checkbox") {
                    if (value == true)
                    {
                        $('input:checkbox[name=' + o.name + ']').attr('checked', true);
                    }
                    else
                    {
                        $('input:checkbox[name=' + o.name + ']').attr('checked', false);
                    }
                    isSeted = true;
                }
                else if (o.controltype == "text") {
                    $('#' + o.name).attr("value", value);
                    isSeted = true;
                }
                else if (o.controltype == "numeric") {
                    var numerictextbox = $("#" + o.name + "").data("kendoNumericTextBox");
                    // bind to the change event
                    numerictextbox.value(value);
                    isSeted = true;
                }
                else if (o.controltype == "date") {
                    var datePicker = $("#" + o.name + "").data("kendoDatePicker");
                    datePicker.value(value);
                    isSeted = true;
                }
                else if (o.controltype == "combobox") {
                    // get a reference to instance of the Kendo UI ComboBox
                    var combobox = $("#" + o.name + "").data("kendoComboBox");
                    combobox.value(value);
                    isSeted = true;
                }
                else if (o.controltype == "lvcombobox") {
                    // get a reference to instance of the Kendo UI ComboBox
                    var combobox = $("#" + o.name + "").LVComboBox().data("LVComboBox");
                    combobox.value(value);
                    isSeted = true;
                }
            }
        });

        if (isSeted == true) return;

        this.SetValueGrid(fieldName, value, focus);
    }

    this.SetValueGrid = function (fieldName, value, focus) {
        if (IsNull(objControlsGrid)) return;
        $(objControlsGrid.data).each(function (i) {
            var o = objControlsGrid.data[i];
            if (o.name == fieldName) {
                for (var j = 0; j < GridViewNamePopup.length; j++) {
                    if (IsNullOrEmty(GridViewNamePopup[i])) continue;
                    if (GridViewNamePopup[j] == o.gridname)
                    {
                        SetValueForGrid(GridViewNamePopup[j], fieldName, value);
                    }
                }
            }

        });
        
    }

    this.GetValue = function (fieldName) {
        var returnValue;
        $(objControls.data).each(function (i) {
            var o = objControls.data[i];
            if (o.name == fieldName) {
                if (o.controltype == "checkbox") {
                    if($('input:checkbox[name=' + o.name + ']').attr('checked')=='checked')
                        returnValue=true;
                    else
                        returnValue = false;
                        
                }
                else if (o.controltype == "text") {
                    returnValue= $('#' + o.name).attr("value");
                }
                else if (o.controltype == "numeric") {
                    var numerictextbox = $("#" + o.name + "").data("kendoNumericTextBox");
                    // bind to the change event
                    returnValue= numerictextbox.value();
                }
                else if (o.controltype == "date") {
                    var datePicker = $("#" + o.name + "").data("kendoDatePicker");
                    returnValue= datePicker.value();
                }
                else if (o.controltype == "combobox") {
                    // get a reference to instance of the Kendo UI ComboBox
                    var combobox = $("#" + o.name + "").data("kendoComboBox");
                    returnValue =combobox.value();
                }
                else if (o.controltype == "lvcombobox") {
                    // get a reference to instance of the Kendo UI ComboBox
                    var combobox = $("#" + o.name + "").LVComboBox().data("LVComboBox");
                    returnValue = combobox.value();
                }
                
            }
        });
        return returnValue;
    }

    this.Focus = function (fieldName) {
        var returnValue;
        $(objControls.data).each(function (i) {
            var o = objControls.data[i];
            if (o.name.trim() == fieldName.trim()) {
                if (o.controltype == "checkbox") {
                    $('input:checkbox[name=' + o.name + ']').focus();
                }
                else if (o.controltype == "text") {
                    $('#' + o.name).focus();
                }
                else if (o.controltype == "numeric") {
                    var numerictextbox = $("#" + o.name + "").data("kendoNumericTextBox");
                    // bind to the change event
                    numerictextbox.focus();
                }
                else if (o.controltype == "date") {
                    var datePicker = $("#" + o.name + "").data("kendoDatePicker");
                    datePicker.focus();
                }
                else if (o.controltype == "combobox") {
                    // get a reference to instance of the Kendo UI ComboBox
                    var combobox = $("#" + o.name + "").data("kendoComboBox");
                    combobox.focus();
                }
                else if (o.controltype == "lvcombobox") {
                    // get a reference to instance of the Kendo UI ComboBox
                    var combobox = $("#" + o.name + "").LVComboBox().data("LVComboBox");
                    combobox.focus();
                }
            }
        });
    }

    this.SetPredicateForCombo = function (fieldName, fieldsource, value) {
        
        // get a reference to instance of the Kendo UI ComboBox
        var combobox = $("#" + fieldName + "").data("kendoComboBox");
                    
        combobox.dataSource.filter({ field: fieldsource, operator: "IsEqualTo", value: value });
        
    }

    //Predicates
    //Ex: [{ field: "VATGroupID", operator: "startswith", value: "111" }, { field: "ABC", operator: "StartsWith", value: "1" }]
    this.SetMultiPredicateForCombo = function (fieldName, Predicates)
    {
        // get a reference to instance of the Kendo UI ComboBox
        var combobox = $("#" + fieldName + "").data("kendoComboBox");
        var objfilter = $.parseJSON(Predicates);
        combobox.dataSource.filter(objfilter);  
        
    }

    //codeBasePopup.SetMultiPredicateComplexForCombo("CashAcctID", "(AccountID.IndexOf(~0)==0||AccountID.IndexOf(~1)==0||AccountID.IndexOf(~2)==0)&&!AccountID.Equals(~3)&&Detail.Equals(~4)", "1|4|5|111|true");
    this.SetMultiPredicateComplexForCombo = function (fieldName, Predicates,values) {
        var combobox = $("#" + fieldName + "").data("kendoComboBox");
        // get a reference to instance of the Kendo UI ComboBox
        combobox.dataSource.filter({ field: Predicates, operator: "IsEqualTo", value: values });
    }

    this.SetEntityDetail = function (_entityDetail)
    {
        this.entityDetail = _entityDetail.split(",");
    }

    this.SetViewBagEdit = function (_ViewBagEditl) {
        this.ViewBagEdit = _ViewBagEditl;
    }

    this.GetViewBagEdit = function () {
        return this.ViewBagEdit;
    }

    this.OrderTab = "";

    this.setOrderTab = function (_OrderTab)
    {
        this.OrderTab = _OrderTab;
    }

    function lostFocus(name)
    {
        if (typeof onLostFocus != "undefined")
        {
            onLostFocus(name);
        }
    }

    function keyDown(e,name )
    {

        if (this.codeBasePopup.OrderTab != "") {
            if (e.keyCode == 9) {
                $(objControls.data).each(function (i) {
                    var o = objControls.data[i];
                    if (o.name.trim() == name.trim() && o.controltype == "combobox")
                    {
                        var combobox = $("#" + o.name + "").data("kendoComboBox");
                        combobox.close();
                        combobox.focus();
                    }
                });
                    var nextControl = "";
                    var c = this.codeBasePopup.OrderTab.split(",");
                    if (e.shiftKey == false) {
                        for (i = 0; i < c.length - 1; i++) {
                            if (c[i].trim() == name) {
                                nextControl = c[i + 1].trim();
                                if (this.codeBasePopup.CheckReadOnly(nextControl))
                                {
                                    name = nextControl;
                                    nextControl = "";
                                }
                            }
                        };
                    }
                    else
                    {
                        for (i = c.length - 1; i >0; i--) {
                            if (c[i].trim() == name) {
                                nextControl = c[i - 1].trim();
                                if (this.codeBasePopup.CheckReadOnly(nextControl)) {
                                    name = nextControl;
                                    nextControl = "";
                                }
                            }
                        };
                    }

                    if (nextControl != "") {
                        setTimeout($.proxy(function () { this.codeBasePopup.Focus(nextControl); },this),10);
                        
                        e.keyCode = 0;
                        e.preventDefault(e);
                        e.returnValue = false;
                        e.stopPropagation();
                    }
                }
        }
    }

    this.GetValueFromModel = function (fieldName) {
        if (GridViewNamePopup == "") return;

        var gridview = $("#" + GridViewNamePopup).data("kendoGrid");

        var model = GetCurrentRowEx(gridview);
        if (!IsNull(model))
            return model[fieldName];
        else
            return null;

    }

    this.Print = function (Module, dataSet, ReportName, Title, storeName, para) {
        para = para.replace(' ', '%20');

        var url = GetBaseUrl() + "ReportViewer.aspx?Module=" + Module + "&EntityName=" + dataSet + "&ReportName=" + ReportName + "&FormTitle=" + Title + "&StoreProcedure=" + storeName + '&' + para;


        window.open(url);
    };
}
